package utils

import (
	"bytes"
	"io"
	"io/ioutil"
	"net/http"
)

var client *http.Client

func init() {
	client = &http.Client{}
}

// SetSimpalHeader set http header
func SetSimpalHeader(headMap map[string]string, request *http.Request) {
	for k, v := range headMap {
		request.Header.Add(k, v)
	}
}

// DoHTTP do a http request
func DoBytes(method string, url string, headMap map[string]string, dataBody string) (result []byte, code int, err error) {
	resp, err := DoResp(method, url, headMap, dataBody)
	if err != nil {
		return
	}

	defer resp.Body.Close()
	code = resp.StatusCode
	result, err = ioutil.ReadAll(resp.Body)

	return
}

// DoHTTP do a http request
func DoResp(method string, url string, headMap map[string]string, dataBody string) (resp *http.Response, err error) {
	var body io.Reader
	if dataBody != "" {
		body = bytes.NewBuffer([]byte(dataBody))
	}
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return
	}

	if len(headMap) > 0 {
		SetSimpalHeader(headMap, req)

	}
	resp, err = client.Do(req)
	return
}
